﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core.Sugar;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.Shop.Data.Repositories;
using StructureMap;
using DropDownList = System.Web.UI.WebControls.DropDownList;

namespace Medianamik.UI.Web.Shop.Controls
{
    public class BrandDropDownList : BrandDropDownList<Data.Interfaces.IBrand>
    {
    }

    public class BrandDropDownList<TBrand> : BaseMedianamikControl
        where TBrand : Data.Interfaces.IBrand
    {
        private readonly IBrandRepository<TBrand> _brandRepository = ObjectFactory.GetInstance<IBrandRepository<TBrand>>();

        private readonly DropDownList _ddl = new DropDownList
        {
            ID = ControlToValidateId,
            CssClass = "SelectList"
        };

        public override object GetValue()
        {
            Guid g;
            return _ddl.Items.Cast<ListItem>()
                .Where(i => i.Selected && StringHelper.IsGuid(i.Value, out g))
                .Select(i => (Guid?)new Guid(i.Value))
                .FirstOrDefault();
        }

        public override void SetValue(object value)
        {
            _ddl.SelectedValue = value != null ? value.ToString() : string.Empty;
        }

        public override Type TypeOfValue
        {
            get { return typeof(Guid?); }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_ddl);

            if (pUseDataSource)
            {
                var brands = _brandRepository.GetBrandsWithParent();

                if (brands.Count > 0)
                {
                    foreach (var brand in brands)
                    {
                        var item = new ListItem(brand.Name, brand.NodeId.ToString());
                        _ddl.Items.Add(item);
                    }
                }
                _ddl.Items.Insert(0, new ListItem("", Guid.Empty.ToString()));

                var selectedValue = (Guid?)DataSource;
                if (selectedValue.HasValue)
                {
                    var item = _ddl.Items.FindByValue(selectedValue.Value.ToString());
                    if (item != null) { item.Selected = true; }
                }
            }
        }
    }
}
